

var app = getApp()
var fun = require('../fun.js');
Page({
  data: {
    nav:{top:app.globalData.nav_top,title:'',home:'hide',back:'show',safe_top:app.globalData.safe_top,bottom:app.globalData.safe_bottom,page:'detail'},page:1,can_load:1,share_bt:'1',can_buy:0,msg:{total:0,page:1,num:0},more_msg_text:'查看更多留言'
  },

  onLoad: function (op) {
var from='direct';//从哪里来
var id=op.id;if(!id){id=0;from='link';}//门店
var from_id=op.f;if(!from_id){from_id=0;}//来源id
    if (op.scene) {//扫描
      var scene = decodeURIComponent(op.scene);
      var arrPara = scene.split("&");
      var arr = [];
      for (var i in arrPara) {
        arr = arrPara[i].split("=");
        if (arr[0] == 'f') { from_id = arr[1]; }//from_id
        if (arr[0] == 'id') { id=arr[1];}//门店id
      }
     from='scan';
    }
app.globalData.from=from;
app.globalData.from_id=from_id;
if(!id){app.err('请指定活动');return;}
this.data.id=id;//门店id

wx.setNavigationBarColor({//设置胶囊按钮
  frontColor: '#ffffff',
  backgroundColor: '#ff0000',
})

  },

  onReady: function () {
   var pages=getCurrentPages();
this.setData({page_num:Object.keys(pages).length})

    this.load();
fun.get_pos().then(res=>{
if(res.err=='ok'){//用户的经纬度
  app.globalData.latitude=res.latitude; 
  app.globalData.longitude=res.longitude;
var shop=this.data.shop;
if(shop && shop.latitude){
var dis=fun.get_dis(app.globalData.latitude,app.globalData.longitude,shop.latitude,shop.longitude);
this.setData({dis:dis});
}
}
  })
  },

  onShow: function () {
    if(app.globalData.clean_cart==1){//如果有提示需要清除订单
      var list=this.data.list;
      this.setData({total:'0.00',cart_num:0,cart:{}})
      this.format_cart()
    try {wx.setStorageSync('cart_'+list.id, JSON.stringify({}))} catch (e) {}//缓存
    }

if(app.globalData.flash==1){this.load();}

var time=this.data.time;
if(time){this.set_time(time);}
var reload=this.data.reload;
if(reload>0){this.reload();}
app.globalData.flash=0;app.globalData.clean_cart=0;
  },

  load: function () {
var id=this.data.id;var that=this;
this.setData({quan_show:''})
fun.get({ac:'get_hd_detail',id:id,path:'hd'}).then(res=>{
  this.setData({list:res.list,
  user:res.user,
  shop:res.shop,
  quan:res.quan,//优惠券
  my_quan:res.my_quan,//我的优惠券
  app:res.app,
  can_edit:res.can_edit,
  pro:res.pro,
  mz:res.mz,//满赠
  miao:res.miao//秒杀
  ,share:res.share,
  can_buy:res.can_buy,
  time:res.time,
  reload:res.reload,
  order:res.order,
  info:res.info,
  order_num:res.order_num,
  order_page:1,
  my_order_num:res.my_order_num,//我的订单数
  msg:res.msg?res.msg:{total:0,page:1,num:0},//留言
  quan_show:res.quan_show,
  need_gz:res.need_gz,//订阅
  })
if(!res.user){this.login();}
if(app.globalData.latitude && res.shop &&  res.shop.latitude){
  var dis=fun.get_dis(app.globalData.latitude,app.globalData.longitude,res.shop.latitude,res.shop.longitude);
  this.setData({dis:dis});console.log('距离',dis)
}

  var cart=wx.getStorageSync('cart_'+res.list.id);//获取购物车
  if(cart){
  var cart=JSON.parse(cart);
  this.setData({cart:cart})
  console.log('初始化购物车',cart)
  this.format_cart()
  }
if(res.time){this.set_time(res.time)}//倒计时
//如果活动存在reload时间，则进行定时更新
if(res.reload>0){ clearTimeout(this.data.reload_time);
  this.data.reload_time=setTimeout(function(){that.reload()},res.reload);
}
//this.draw_hb()
})
  },


draw_hb(){//绘制海报
var list=this.data.list;
var that=this;
if(list.img){
//this.draw(0);
fun.get({ac:'get_qr_data',path:'hd',id:list.id,server:app.globalData.server}).then(res=>{//获取二维码数据
//获取二维码图片
this.data.qr=res.qr;
this.setData({hb_show:'show'})
for(var i in list.img){
   var query = wx.createSelectorQuery();
   query.select('#hb_'+i).fields({
      id: true,
      node: true,
      size: true
    }).exec(this.draw.bind(this));
}
})
}else{app.err('抱歉，该活动没有设置海报');}
},
draw(res){var that=this;
   var list=this.data.list;
   var user=this.data.user;
   var index=res[0].id.replace('hb_','');
   console.log('海报',res,res[0].id,index)
   const canvas = res[0].node
   const ctx = canvas.getContext('2d')
   const dpr = wx.getSystemInfoSync().pixelRatio;
   var width=750;
   var height=1000;
   if(!this.data.qr_data){
   var qr_data=canvas.createImage();
   qr_data.src =this.data.qr;
   qr_data.onload = () => {this.data.qr_data=qr_data;}
}
//获取图片信息
var img = canvas.createImage();
img.src =list.img[index].img_750;
console.log(img.src)
img.onload = () => {
console.log('图片尺寸',img.src,img.width,img.height)
height=img.height+500;
//画板尺寸
canvas.width = width;
canvas.height = height;
var hb_size=this.data.hb_size;
if(!hb_size){hb_size={}}
hb_size[index]={width:width,height:height}

this.setData({hb_size:hb_size})

var img_height=canvas.width*img.height/img.width;//图片的高度
console.log('高度',img_height,canvas.width)
//背景
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width,  canvas.height);
ctx.drawImage(img,0,0,750,img.height,0,0,canvas.width,img_height);

ctx.moveTo(0,0);
//标题
ctx.font = 'normal bold 50px sans-serif';
ctx.fillStyle = "rgba(0, 0, 0)";
//文本尺寸
var line=0;var line_height=70;var metrics=0;
var lines=[[canvas.width-400,canvas.width-300],[canvas.width-350,canvas.width-250],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50],[canvas.width-100,canvas.width-50]];
var title=Array.from(list.title)
//console.log(title)
var title_data='';
var text_height=0;
var text_width=ctx.measureText(list.title);
if(text_width.width<(canvas.width-400)){//直接写入
   console.log('直接写')
   ctx.fillText(list.title,30,img_height+line_height);
}else{
for(var i in title){
var line_data=lines[line];
title_data+=title[i];
metrics =ctx.measureText(title_data);
console.log(title_data,line_data,line,metrics)
if(metrics.width>=line_data[0] && metrics.width<=line_data[1]){//输出
 // console.log('蔬菜')
 text_height=img_height+line_height*(line+1);
 console.log('文本高度',text_height)
   ctx.fillText(title_data,30,text_height);
   title_data='';line++;
   if(line>=3){break;}
}
}
}




var text='￥'+list.min+' - '+list.max;
ctx.font = 'normal bold 60px sans-serif';
ctx.fillStyle = "crimson";
text_height=canvas.height-100;
ctx.fillText(text,30,text_height);
if(list.end_time){
ctx.font = 'normal  30px sans-serif';
ctx.fillStyle = "#999";
text_height+=50;
ctx.fillText('截止日期:'+list.end_time,35,text_height);
}
ctx.restore();
ctx.save();
ctx.beginPath();
//画购买符号
var x=canvas.width-180;var y=img_height+300;var w=120;var r=60;var h=120;
ctx.moveTo(x,y);
ctx.arcTo(x+w,y,x+w,y+h,r);
ctx.arcTo(x+w,y+h,x,y+h,r);
ctx.arcTo(x,y+h,x,y,r);
ctx.arcTo(x,y,x+w,y,r);
ctx.clip();
ctx.fillStyle = '#00a47c';
ctx.fillRect(x, y,w,h);
ctx.closePath();
//添加文本
ctx.font = 'normal  100px sans-serif';
ctx.fillStyle ='#ffffff';
var text='+';
var measureText=ctx.measureText(text);
ctx.fillText(text,x+30,y+90);
ctx.restore();
//画圆



ctx.save();
ctx.beginPath();
var x=canvas.width-350;var y=img_height-150;var w=300;var r=150;var h=300;
ctx.moveTo(x,y);
ctx.arcTo(x+w,y,x+w,y+h,r);
ctx.arcTo(x+w,y+h,x,y+h,r);
ctx.arcTo(x,y+h,x,y,r);
ctx.arcTo(x,y,x+w,y,r);
ctx.clip();
ctx.fillStyle = 'white';
ctx.fillRect(x, y,w,h);
ctx.closePath();

//画二维码
if(this.data.qr_data){
   ctx.drawImage(this.data.qr_data,x+25,y+25,250,250);
}else{
var qr_data=canvas.createImage();
qr_data.src =this.data.qr;
qr_data.onload = () => {this.data.qr_data=qr_data;
   ctx.drawImage(qr_data,x+25,y+25,250,250);
}
}

ctx.restore();
//画用户logo

if(user){
var user_logo=canvas.createImage();
user_logo.src=user.logo;
user_logo.onload = () => {
   ctx.beginPath();
   var x=30;var y=30;var w=120;var r=60;var h=120;
   ctx.moveTo(x,y);
   ctx.arcTo(x+w,y,x+w,y+h,r);
   ctx.arcTo(x+w,y+h,x,y+h,r);
   ctx.arcTo(x,y+h,x,y,r);
   ctx.arcTo(x,y,x+w,y,r);
   ctx.clip();
   ctx.fillStyle = 'white';
   ctx.fillRect(x, y,w,h);
   ctx.drawImage(user_logo,x,y,w,h);

}
}

//保存到本地
setTimeout(function(){
wx.canvasToTempFilePath({x:0,y:0,canvas:canvas,fileType:'png',success(res){
that.data['cavans_'+index]=res.tempFilePath;
console.log('保存本地路径',res)
}})

},300)

}



},
hb_save(e){//保存图片
   console.log('保存海报');
   var index=this.data.hb_index;if(!index){index=0;}
   var cav=this.data['cavans_'+index]
   wx.getSetting({success(res){console.log(res)
//if(res.authSetting['scope.writePhotosAlbum']){
   app.msg('图片保存中，请稍后');
wx.saveImageToPhotosAlbum({filePath:cav})
//}else{app.msg('抱歉，您没有打开保存到本地相册的权限');}

   }})


       },


  reload(){//重新获取活动的商品等数据
var list=this.data.list;var that=this;
fun.get({ac:'get_hd_detail',path:'hd',c:'reload',id:list.id}).then(res=>{
 this.setData({
    list: res.list,
    pro: res.pro,//更新商品库存
    mz: res.mz,//满赠
    miao: res.miao,//秒杀库存等
    can_buy: res.can_buy,//是否可以购买
    reload: res.reload,
    order_num:res.order_num,
    msg:res.msg?res.msg:{total:0,page:1,num:0},
    can_edit:res.can_edit,
    user:res.user
  });
var order_page=this.data.order_page;
if(order_page>1){}else{//如果订单有进行查找更多的，将不进行更新订单
this.setData({order: res.order})
}
    this.format_cart();//处理订单
    if(res.reload>0){
      clearTimeout(this.data.reload_time);
      this.data.reload_time=setTimeout(function(){that.reload()},res.reload);
      }
})
  },
  get_more_order(e){console.log('获取更多订单数据')
var order_page=this.data.order_page;if(!order_page){order_page=1;}
var order_num=this.data.order_num;//如果订单数量小于10，则不读取
//if(order_num<10){return;}
var go_read_order=this.data.go_read_order;
if(go_read_order==1){return;}//是否正在读取
var list=this.data.list;
order_page++;
this.data.go_read_order=1;
fun.get({ac:'get_more_order',path:'hd',id:list.id,page:order_page}).then(res=>{
if(res.order){
var order=this.data.order;if(!order){order=[]}
for(var i in res.order){
  order.push(res.order[i]);
}
this.data.go_read_order=0;this.data.order_page=order_page;
this.setData({order:order,order_num:res.order_num})
}else{
this.setData({order_num:0})
}
})

  },
  
  
  
  set_time(val){//设置倒计时
    var that=this;
var now=(new Date()).getTime()/1000;
var l=Math.floor(val-now);//console.log(l)
if(l<0){var list=this.data.list;
if(list.is_start==1){//开始，则进行结束庄园
this.load();
return;
}else{
list.hd_state='抱歉，该活动已经结束';this.setData({list:res.list,time_show:'',can_buy:0});return;}}//活动结束
var time_show={}
time_show.year=Math.floor(l/(3600*24*365));if(!time_show.year){time_show.year=0;}
l=l-time_show.year*3600*24*365;
time_show.days=Math.floor(l/(3600*24));if(!time_show.days){time_show.days=0;}
l=l-time_show.days*3600*24;
time_show.hour=Math.floor(l/3600);if(!time_show.hour){time_show.hour=0;}
l=l-time_show.hour*3600;
time_show.minit=Math.floor(l/60);if(!time_show.minit){time_show.minit=0;}
l=l-time_show.minit*60;
time_show.second=l;
//console.log(time_show)
this.setData({time_show:time_show});
this.data.time_show=setTimeout(function(){that.set_time(val)},1000)
  },
  cart_add(e){//加入到购物车
    var cart=this.data.cart;if(!cart){cart={}}
    var c=e.currentTarget.dataset.c;
    var ac=e.currentTarget.dataset.ac;if(ac!='jian'){ac='add';}
    if(c=='miao'){//秒杀
    var miao=this.data.miao;
    if(!miao){return;}
    if(cart.miao && cart.miao.buy>0){return;}
    cart.miao={buy:1,id:miao.pro.id,total:miao.price};
this.setData({miao:miao,cart:cart});
this.format_cart();
    }else{//商品添加
      if(!cart.pro){cart.pro={}}
    var pro=this.data.pro;if(pro.data){this.open_select_data(e);return;}//如果存在商品属性，则打开属性窗口
    var index=e.currentTarget.dataset.index;
    var price=parseFloat(pro[index].price);
if(cart.pro[index]){//购买数量
var buy=parseInt(cart.pro[index].buy);//已经后购买
}else{
var buy=0;
}
    var max=parseInt(pro.total);//商品数量
    if(ac=='add'){
      if(max==0){app.msg(pro.title+'已经售罄');return;}//售罄
      buy++
if(max>0 && buy>max){app.msg('超过库存');buy=max;}//超过库存，则显示信息，并选择最大值
  }else{//减少商品
    buy--;
    if(buy<=0){buy=0;}
  }
var total=price*buy;
total=fun.number_fromat(total,2)
cart.pro[index]={buy:buy,id:pro[index].id,total:total}
this.setData({cart:cart});
console.log(cart,price,total,pro)
this.format_cart();
    }//
  },
  select_cart_add(e){
var cart=this.data.cart;if(!cart){cart={}}
var index=e.currentTarget.dataset.index;
var pros=this.data.pro;
var pro=pros[index];if(!pro){app.msg('没有找到商品');return;}
if(!pro.data){this.cart_add(e);return;}
var c=this.data.is_select_c;var sub_index=this.data.sub_index;
var buy=this.data.select_num;if(!buy){buy=1;}
if(!c){app.msg('参数错误');return;}
var info='';
if(!pro.data[c]){app.msg('参数错误');return;}//没有分类
if(pro.data[c]['item']){//存在内
var max=parseInt(pro.data[c]['item'][sub_index].num);
var price=parseFloat(pro.data[c]['item'][sub_index].price);
info=c+' '+pro.data[c]['item'][sub_index].title;
}else{sub_index='';
var max=parseInt(pro.data[c].num);
var price=parseFloat(pro.data[c].price);
if(!price){price=parseFloat(pro.price)}
info=c;
}
if(max==0){app.msg('超过库存');return;}
if(max>0 && buy>max){buy=max;}
//订单内部添加 数量和总金额重新计算
if(!cart.pro){cart.pro={}}
if(!cart.pro[index]){cart.pro[index]={buy:1,id:pro.id,total:0,data:{}}}
if(!cart.pro[index]['data'][c]){cart.pro[index]['data'][c]={}}
if(!cart.pro[index]['data'][c]['item_'+sub_index]){cart.pro[index]['data'][c]['item_'+sub_index]={}}
var is_buy=parseInt(cart.pro[index]['data'][c]['item_'+sub_index].buy);//是否已经购买
if(!is_buy){is_buy=0;}
buy+=is_buy;
var total=price*buy;
total=fun.number_fromat(total,2);
price=fun.number_fromat(price,2);
cart.pro[index]['data'][c]['item_'+sub_index]={info:info,price:price,buy:buy,total:total}
this.setData({cart:cart,pro_select_show:''});
this.format_cart();//进行格式化 并进行金额数量，已经缓存
console.log(index,pro,c,sub_index,cart)
  },

  format_cart(e){//对订单进行处理
    var cart=this.data.cart;
    if(!cart){console.log('不存在订单');return;}
    var list=this.data.list;
    var total=0;//总金额
    var pro_price=0;//商品金额
    var cart_num=0;//数量
var can_buy=0;
if(cart.miao && cart.miao.buy>0){//存在秒杀
  if(cart.miao.buy==1){//秒杀了 秒杀仅限一件
    var miao=this.data.miao;
    if(miao.total==0){//已经抢光
      cart.miao={}
    }else{
  var price=parseFloat(cart.miao.total);
  cart_num+=1;
  pro_price+=price;}
  }else{cart.miao={}}
}

if(cart.pro){
var pros=this.data.pro;//商品
var pro=cart.pro;
for(var i in pro){
var temp_pro=pros[i];//商品
if(!temp_pro){delete(cart.pro[i]);}else{//如果不存在商品,则删除购物车商品
//存在商品
if(pro[i].data){//存在分类,对分类进行分析格式化，并计算出总金额和销量
console.log('存在分类',pro[i].data,Object.keys(pro[i].data).length)
if(Object.keys(pro[i].data).length==0){delete(cart.pro[i]);}else{//没有数据
  //存在数据，则进行计算
  var temp_num=0;var temp_total=0;
for(var j in pro[i].data){
if(Object.keys(pro[i].data[j]).length==0){delete(cart.pro[i].data[j]);}else{//在不存在子项目，则删除
//对子
let temp_data=pro[i].data[j];
for(var x in temp_data){
var temp_x=x.replace('item_','');
if(temp_x==''){//不存在子分类
var max=parseInt(temp_pro.data[j].num);//不存在自分类的数量
}else{console.log('获取数量')
   var max=0;
   try {var max=parseInt(temp_pro.data[j]['item'][temp_x].num);//商品数量
}catch (e){}//缓存

}
//console.log('参数',x,j,i,temp_x,'数量',max,temp_pro)
var buy=parseInt(temp_data[x].buy);
var tt=parseFloat(temp_data[x].total);
if(buy==0){//商品数量不存在
  console.log('删除商品',j,x)
  delete(cart.pro[i].data[j][x]);
}else{
if(max==0){app.msg(temp_pro.title+'已经售罄');delete(cart.pro[i].data[j][x]);}else{//如果没有库存商品
  
if(max>0 && buy>max){app.msg(temp_pro.title+'超过库存');
cart.pro[i].data[j][x].buy=max;
buy=max;}//修改数量

cart_num+=buy;
pro_price+=tt;
temp_num+=buy;
temp_total+=tt;
console.log(buy,tt);
  }
}
}
}
}
//对计算的结果进行汇总
cart.pro[i]['buy']=temp_num;
cart.pro[i]['total']=temp_total;can_buy++;
}
}else{//不存在分类,则直接计算金额
var buy=parseInt(pro[i].buy);
var tt=parseFloat(pro[i].total);
var price=parseFloat(temp_pro.price);
if(buy==0){//商品数量不存在
  delete(cart.pro[i]);
console.log('删除商品')
}else{
  var max=parseInt(temp_pro.total);
  if(max==0){app.msg(temp_pro.title+'售罄');delete(cart.pro[i]);}else{
  if(max>0 && buy>max){app.msg(temp_pro.title+'超过库存');buy=max;
  cart.pro[i].buy=max;
}//超过库存

cart_num+=buy;
pro_price+=buy*price;can_buy++;
  }

}
}
}
}//存在商品

}
//是否进行满赠
var mz=this.data.mz;
if(mz){
if(pro_price>0 && pro_price>=mz.price && mz.pro && mz.total!=0){
  console.log('满足满赠条件')
  cart['mz']={buy:1,id:mz.pro.id,total:0}
  cart_num+=1;
}else{
  console.log('满赠取消')
  cart['mz']={}
}
}
//优惠券信息
var quan=this.data.my_quan;var quan_price=0;cart.quan={}
if(quan){
for(var i in quan){
//按条件选择满赠的优惠券
if(pro_price>=quan[i]['man'] && quan[i]['man']>0){
  quan_price=quan[i].price;
  cart.quan=quan[i];
}
}
}

//运费 也可以根据距离进行计算金额
var yun=this.data.yun;
var yun_price=0;
if(yun && yun.is_ps==1){
  yun_price=parseFloat(yun.ps_price);
  var baoyou=parseFloat(yun.ps_baoyou);
  if(yun_price>0){
if(baoyou>0 && pro_price>=baoyou){//是否包邮
  yun_price=0;
}
  }
}


total=pro_price-quan_price+yun_price;
total=fun.number_fromat(total,2);
var cart_total=parseFloat(this.data.total);if(!cart_total){cart_total=0;}
if(can_buy>0){can_buy=1;}
this.setData({total:total,cart_num:cart_num,cart:cart,can_buy:can_buy});
try {wx.setStorageSync('cart_'+list.id, JSON.stringify(cart))}catch (e){}//缓存
console.log('购物车数据',cart,total,cart_num)
//this.show_total(cart_total,total,0);
  },
  show_total(start,end,step){//显示最新价格s 价格开始，
  var that=this;
  if(start==end){this.setData({show_total:end});return;}
  var s=(end-start)/20;
var price=start+s*step;var is_end=0;
if(start>end){//如果价格
  if(price<end){price=end;is_end++;}
}else{
  if(price>end){price=end;is_end++;}
}
print=fun.number_fromat(price,2);
this.setData({show_total:price});
if(is_end){return;}
step++;
setTimeout(function(){that.show_total(start,end,step)},10);
  },


  miao_del(e){//取消秒杀商品
    var cart=this.data.cart;
    if(!cart.miao){return;}
    var that=this;
    wx.showModal({
      title: '提示',content:'是否取消秒杀商品？',success(res){
        if(res.confirm){
          cart.miao={};
          that.setData({cart:cart});
          that.format_cart()
        }
      }
    })
  },


  cart_num_add(e){//购物车数量增减
var ac=e.currentTarget.dataset.ac;
var index=e.currentTarget.dataset.index;
var cart=this.data.cart;if(!cart){return;}
if(!cart.pro){return;}
 var val=parseInt(e.currentTarget.dataset.val);
 if(val!=-1){val=1;}
if(ac=='data'){//含有数据的添加商品数量
var c=e.currentTarget.dataset.c;
var ins=e.currentTarget.dataset.ins;
console.log(c,ins,index)
if(!cart.pro[index]['data'][c][ins]){app.msg('数据错误');return;}
var buy=parseInt(cart.pro[index]['data'][c][ins].buy)
buy=buy+val;if(buy<=0){buy=0;}
cart.pro[index]['data'][c][ins].buy=buy;
}else{//普通添加数量
var buy=parseInt(cart.pro[index].buy);
buy=buy+val;if(buy<=0){buy=0;}
cart.pro[index].buy=buy;
}
this.setData({cart:cart})
this.format_cart()
  },
  open_select_data(e){//打开选择数据
var pro=this.data.pro;
var index=e.currentTarget.dataset.index;
var select_pro=pro[index];if(!select_pro.data){app.msg('参数错误');return;}
var c='';var sub_index=0;
for(var i in select_pro.data){//默认的分类
if(!c){
  if(select_pro.data[i]['item'] || select_pro.data[i]['num']!=0){c=i;}
}
}

//获取subindex
if(c){
if(select_pro.data[c]['item']){//存在自分类
var item=select_pro.data[c]['item'];
for(var i in item){
if(!sub_index && item.num!=0){sub_index=i;}
}
}
}
this.setData({pro_select_show:'show',select_pro:select_pro,pro_index:index,is_select_c:c,sub_index:sub_index})
console.log('数据',index,select_pro,c,sub_index)
this.get_data_price(c,sub_index);
  },
 select_this_c(e){//选择1级分类
 var c=e.currentTarget.dataset.c;
 var pro=this.data.select_pro;
 var sub_index='';
 if(pro.data[c].item){
var item=pro.data[c].item;//获取自选项
for(var i in item){
  if(sub_index=='' && item[i].num!=0){sub_index=i;}
  }
 }
 console.log('选择的分类',c,sub_index)
this.setData({is_select_c:c,sub_index:sub_index,select_num:1})
this.get_data_price(c,sub_index);
  },
  select_this_sub(e){
  var index=e.currentTarget.dataset.index;
  var c=this.data.is_select_c;
  var pro=this.data.select_pro;
  if(!pro.data[c]['item']){index=0;}console.log(pro.data[c]['item'])
  if(pro.data[c]['item'][index].num==0){return;}//数量为0
this.setData({sub_index:index,select_num:1});
this.get_data_price(c,index)
  },
get_data_price(c,i){//获取参数  级价格
if(!c){app.msg('数据错误，请联系管理处理');return;}
var price=0;var num=this.data.select_num;if(!num){num=1;}
var info='选择:';var total=0;
var pro=this.data.select_pro;
if(pro.data[c].item){
  console.log(pro.data[c]['item'][i]);
  var price=parseFloat(pro.data[c]['item'][i].price);
  if(!price){price=parseFloat(pro.price);}//如果金额没有设置，则选择商品价格
  var max=parseInt(pro.data[c]['item'][i].num);
  info+=c+' '+pro.data[c]['item'][i].title;
}else{
  var price=parseFloat(pro.data[c].price);
  if(!price){price=parseFloat(pro.price);}//如果金额没有设置，则选择商品价格
  var max=parseInt(pro.data[c].num);
  info+=c;
  console.log(pro.data[c],price,max)
}
if(num>max && max>0){num=max;app.msg('超过库存');}
if(max==0){app.msg(pro.title+'已经售罄');return;}
price=fun.number_fromat(price,2);
var total=price*num;
total=fun.number_fromat(total,2);
this.setData({select_price:price,select_total:total,select_num:num,select_info:info});

},
select_num_add(e){//增加数量
var num=parseInt(this.data.select_num);
if(!num){num=1;}
var c=e.currentTarget.dataset.c;
if(c=='add'){num++;}else{
num--;
if(num<=0){num=1;}
}
this.setData({select_num:num})
this.get_data_price(this.data.is_select_c,this.data.sub_index);
},


  clean_cart(e){
  var that=this;var list=this.data.list;
wx.showModal({
  title: '提醒',content:'是否清空购物车?',success(res){
    if(res.confirm){
      that.setData({total:'0.00',cart_num:0,cart:{}})
      that.format_cart()
try {wx.setStorageSync('cart_'+list.id, JSON.stringify({}))} catch (e) { }//缓存
    }
  }
})

  },

  preview(e){//浏览大图
var url=e.currentTarget.dataset.url;
wx.previewImage({
  urls: [url],
})
  },
  hd_state(e){//对活动进行发布 停用等
var list=this.data.list;
var that=this;
if(list.state==1){//停止
wx.showModal({
  cancelColor: '提示',content:'你是否需要停止此活动？',success(res){
    if(res.confirm){
fun.get({ac:'hd_stop',path:'hd',id:list.id}).then(res=>{
  app.msg('您已经成功结束了活动');
  that.load();that.setData({cz_show:''})
})
    }
  }
});
return;
}
//开启活动
fun.get({ac:'hd_start',path:'hd',id:list.id}).then(res=>{
  //app.msg('活动开启成功');
  this.load();this.setData({cz_show:''})
})
  },
  hd_del(e){
var list=this.data.list;
var that=this;
wx.showModal({
  cancelColor: '警告',content:'你是否需要删除该活动，如果您的活动已经存在订单，将无法删除，是否继续？',success(res){
    if(res.confirm){
      fun.get({ac:'hd_del',id:list.id,path:'hd'}).then(res=>{
        wx.redirectTo({
          url: '/pages/adm/hd_list',
        })
      })
    }
  }
})

  },
buy(e){
var list=this.data.list;
var cart=this.data.cart;console.log(cart);
if(!cart || !cart.pro ||  Object.keys(cart.pro).length==0){app.err('抱歉，您的购物车里面没有商品，请选择商品后继续。');return;}
fun.get({ac:'cart_submit',path:'hd',id:list.id,data:JSON.stringify(cart)}).then(res=>{
if(res.id>0){
wx.navigateTo({
  url: '/pages/index/cart?id='+res.id,
})}
})
},
quan_get(e){//获取优惠券
var list=this.data.list;
fun.get({ac:'get_hd_quan',id:list.id,path:'hd'}).then(res=>{
this.load();
this.setData({quan_show:''})
})
},
gz_this(e){//关注这个门店
  var shop=this.data.shop;
fun.get({ac:'gz_this_shop',path:'hd',id:shop.id}).then(res=>{
  app.msg('订阅成功');
  this.setData({need_gz:''})
})

},
  onUnload: function () {

  },
  msg_input(e){
var val=e.detail.value;
console.log(val)
this.setData({msg_inout:val})
  },
  submit_msg(e){
   var val=this.data.msg_inout;
   if(!val){app.msg('请输入您的感受');return;}
   var list=this.data.list;
   fun.get({ac:'submit_msg',id:list.id,val:val,path:'hd'}).then(res=>{
     app.msg('您的留言提交成功，非常感谢您的支持');
     this.setData({msg_input_show:''})
   }) 
  },
  more_msg(e){//获取更多留言
var list=this.data.list;
var msg=this.data.msg;
var total=parseInt(msg.total);
var num=parseInt(msg.num);var page=parseInt(msg.page);
var is_msg_load=this.data.is_msg_load;//正在加载中
if(is_msg_load==1){return;}
this.data.is_msg_load=1;this.setData({more_msg_text:'加载中，请稍后'})
fun.get({ac:'get_more_msg',path:'hd',id:list.id,page:page+1}).then(res=>{
if(res.msg.num>0){
if(!msg.item){msg.item=[]}
for(var i in res.msg.item){
  msg.item.push(res.msg.item[i])
}
msg.total=res.msg.total;
msg.page=res.msg.page;
msg.num=res.msg.num;
var text='查看更多留言';
if(res.msg.num<10){text='留言已经到底';}
this.setData({msg:msg,more_msg_text:text});

this.data.is_msg_load=0;
}

})
  }

,go(e){ 
    var url=e.currentTarget.dataset.url;
    if(!url){app.msg('没有设置链接，请到后台设置或者联系我们');return;}
    wx.navigateTo({url: e.currentTarget.dataset.url})},
  back(e){wx.navigateBack({delta:0})},
  home(e){ wx.reLaunch({url: '/pages/index/index'})},
  rgo(e){wx.redirectTo({url: e.currentTarget.dataset.url})},
  login: function (e) { wx.navigateTo({url: '/pages/login/index'})},
  win_open(e){var c=e.currentTarget.dataset.c;this.setData({[c]:'show'})},//打开窗口
  win_close(e){var c=e.currentTarget.dataset.c;this.setData({[c]:''})},//关闭窗口
open_min(e){wx.navigateToMiniProgram({appId: e.currentTarget.dataset.url,path: '/pages/index/index',})},
scan(e){fun.scan();},
map_go(e){fun.view_add('打开导航');
  var app_info=this.data.app;if(!app_info){app_info={}}
  var key =app.globalData.map_key;
if(app_info.mapkey){key=app_info.mapkey}
if(!key){app.msg('应用没有设置地图API');return;}
    var shop=this.data.shop;
    let plugin = requirePlugin('routePlan');
    let referer = shop.shop_name;
    let endPoint = JSON.stringify({  
      'name': shop.shop_name, 
      'latitude':shop.latitude,
      'longitude': shop.longitude
    });
    wx.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
    });

  },
  call(e){
var shop=this.data.shop
wx.makePhoneCall({
  phoneNumber: shop.phone,
})

  },creat_new(e){//创建新活动
    var list=this.data.list;
    var c=e.currentTarget.dataset.c;
    if(c!='copy'){c='new';}
fun.get({ac:'creat_new_hd',id:list.id,c:c,path:'hd'}).then(res=>{
  wx.redirectTo({
    url: '/pages/index/editor?id='+res.id,
  })
})

  }, onShareAppMessage: function () {//分享
         fun.view_add('打开分享');
         var list=this.data.list;//门店
         var img;var title=list.title;
 
     if(!title){title=app.globalData.app_name}
     
     img=list.img[0]['img_750'];
     if(!img){img='../img/logo.jpg';}
     //用户
         var user_id=app.globalData.user_id;if(!user_id){user_id='';}
         var url='/pages/index/detail?id='+list.id+'&f='+user_id;
       console.log('分享',img,url)
     this.setData({share_box_show:''});//分享按钮窗口关闭
         return {
           title:title,
           path: url,
           imageUrl: img,
         }
       }, onShareTimeline: function () { 
         fun.view_add('分享到朋友圈');
         var list=this.data.list;//门店
         var img;var title=list.title;
 
     if(!title){title=app.globalData.app_name}
     
     img=list.img[0]['img_750'];
     if(!img){img='../img/logo.jpg';}
     //用户
         var user_id=app.globalData.user_id;if(!user_id){user_id='';}
         var url='/pages/index/detail?id='+list.id+'&f='+user_id;
       console.log('分享',img,url)
     this.setData({share_box_show:''});//分享按钮窗口关闭
         return {
           title:title,
           path: url,
           imageUrl: img,
         }
       },hb_change(e){//切换海报后的index
         var val=e.detail.current;
         console.log('切换海报',val)
         this.data.hb_index=val;
         },get_dtl(e){
var pro=this.data.pro;
var index=e.currentTarget.dataset.index;
console.log(pro[index])
this.setData({select_pro:pro[index],dtl_show:true,select_index:index})


         }, onHide:function(){
            console.log('关闭定时器');
  
            clearTimeout(this.data.reload_time);clearTimeout(this.data.time_show);
           },
           onUnload:function(){
            console.log('关闭定时器');
      
            clearTimeout(this.data.reload_time);clearTimeout(this.data.time_show);
           },
})

